import sys
from os.path import exists
from os import mkdir
import os
import csv
import subprocess, shlex
import multiprocessing

HOME_DIR = os.environ['HOME']
DB_ROOT = HOME_DIR + '/data/ddb1_v02_01/'
TRAIN_SET_FILE = HOME_DIR + '/data/ddb1_v02_01/ddb1_v02_01_train_plain.txt'
TEST_SET_FILE = HOME_DIR + '/data/ddb1_v02_01/ddb1_v02_01_test_plain.txt'
TMP_OUT = 'out_dir/'

if not exists(TMP_OUT):
    mkdir(TMP_OUT)

THREADS = multiprocessing.cpu_count()

with open(TEST_SET_FILE, 'r') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ')
    index = 0
    processList = []
    for row in spamreader:
        imgfilename = row[0]
        annotations = row[1:]
        call_str = 'python3 candate.py %s %s %s ' % \
                   (imgfilename, ' '.join(annotations), str(index))
        # os.system(call_str)
        processList.append(subprocess.Popen(shlex.split(call_str)))
        index += 1
        if len(processList) >= THREADS:
            while 1:
                processEnd = False
                for p in processList:
                    try:
                        returncode = p.wait(0.1)
                        if returncode != None:
                            processList.remove(p)
                            processEnd = True
                    except subprocess.TimeoutExpired:
                        pass
                if processEnd:
                    break
    for i in processList:
        i.wait()
